//post
import api from "./config.js"
import CryptoJS from 'crypto-js';

const objectToQueryString = (obj) => {
	return Object.keys(obj).map(function(key) {
		return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(obj[key]));
	}).join('&');
};


const parseParams = (data) => {
	for (const paramsKey in data) {
		if (typeof data[paramsKey] === 'object') {
			data[paramsKey] = encodeURIComponent(data[paramsKey])
		}
	}
	return data
}

const getSignature = (data, secretKey) => {
	return CryptoJS.MD5(data + secretKey).toString();
}

export const post = (url, params = {}, data = {}, load = true) => {

	if (load) {

		// uni.showLoading({
		// 	mask: true,
		// 	title: '加载中'
		// })
	}
	let token = uni.getStorageSync('token')
	// console.log('token', token)
	// let time = parseInt((new Date()).getTime() / 1000)
	let time = parseInt((new Date()).getTime())
	let redirected = false;

	const dataSign = 'user_small' + 'small' + '2.0' + token +
		time + url;
	// console.log(dataSign)
	const secretKey = "";
	const signature = getSignature(dataSign, secretKey);
	// console.log('请求链接====', api.config)
	var promise = new Promise((resolve, reject) => {
		uni.request({
			url: api.config + url + '?' + objectToQueryString(params),
			data: data,
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'source': 'user_small',
				'platform': 'small',
				'version': '2.0',
				'time': time,
				'token': token,
				'sign': signature
			},
			success(res) {
				if (res.data.code == 401) {
					uni.clearStorageSync();
					uni.hideLoading();
					uni.setStorageSync('token', '')
					uni.setStorageSync('useInfo', '')
					// jmlogin()
					return false
				}
				if (res.data.code == 0) {
					console.log('报错', res)
					if (res.data.msg == '校验未通过,请检查信息或联系客服') {
						uni.$u.toast('校验未通过,请检查信息或联系客服');

						uni.setStorageSync('isDisable', '0'); //实名信息失败了
						return reject(res.data);
					}
					if (res.data.msg == '识别失败,请检查营业执照照片') {
						uni.$u.toast('识别失败,请检查上传的照片');
					}
					if (res.data.msg == '验证码不匹配') {
						uni.$u.toast('验证码不匹配');
					}
					if (res.data.msg == '验证码错误') {
						uni.$u.toast('验证码错误');
					}
					if (res.data.msg == '发送频繁,请稍后再试') {
						uni.$u.toast('验证码发送频繁,请稍后重试');
					}
					resolve(res.data);
					uni.hideLoading();
					return false
				}
				if (res.data.code !== 401 || res.data.code !== 0) {
					resolve(res.data);
					uni.hideLoading();
					return false
				}
				uni.hideLoading();

			},
			fail: (err) => {
				uni.$u.toast('----', '请求失败222，请稍后再试', err);
				uni.hideLoading();
				uni.setStorageSync('token', '')
				uni.setStorageSync('useInfo', '')
				reject(err)
			}

		})
	})
	return promise
}

